import base64, hashlib
from Crypto.Cipher import AES
from wechatpy import WeChatClient
from wechatpy.pay import WeChatPay
from wechatpy.session.memcachedstorage import MemcachedStorage
from .wchat_extra import WeChatExtra
from finance_c2c.local_settings import KaLaiBaoConfig

from .wx_base import mc

session_interface = MemcachedStorage(
    mc,
    prefix="wechatpy"
)


class CostumeWeChatClient(WeChatClient):
    wechat_extra = WeChatExtra()


wechat_client = CostumeWeChatClient(
    KaLaiBaoConfig.miniAppId,
    KaLaiBaoConfig.miniAppSecret,
    session=session_interface
)

# wechat_client_howhow = CostumeWeChatClient(
#     miniAppIdHowho,
#     miniAppSecretHowho,
#     session=session_interface
# )


wechat_client_howhow = CostumeWeChatClient(
    KaLaiBaoConfig.miniAppId,
    KaLaiBaoConfig.miniAppSecret,
    session=session_interface
)

wx_pay = WeChatPay(KaLaiBaoConfig.miniAppId, KaLaiBaoConfig.api_key, KaLaiBaoConfig.mch_id,
                   sub_appid=KaLaiBaoConfig.miniAppId,
                   mch_cert=KaLaiBaoConfig.mch_cert, mch_key=KaLaiBaoConfig.mch_key)


wx_pay_howho = WeChatPay(KaLaiBaoConfig.miniAppId, KaLaiBaoConfig.api_key, KaLaiBaoConfig.mch_id,
                         sub_appid=KaLaiBaoConfig.miniAppId, mch_cert=KaLaiBaoConfig.mch_cert,
                         mch_key=KaLaiBaoConfig.mch_key)


class AESCipher():
    """
    Usage:
        c = AESCipher('password').encrypt('message')
        m = AESCipher('password').decrypt(c)
    Tested under Python 3 and PyCrypto 2.6.1.
    """

    def __init__(self, key):
        self.key = hashlib.md5(key.encode("utf8")).hexdigest()

        # Padding for the input string --not
        # related to encryption itself.
        self.BLOCK_SIZE = 32  # Bytes
        self.pad = lambda s: s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * \
                             chr(self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE)
        self.unpad = lambda s: s[:-ord(s[len(s) - 1:])]

    # 加密
    def encrypt(self, raw):
        raw = self.pad(raw)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return base64.b64encode(cipher.encrypt(raw))

    # 解密，针对微信用此方法即可
    def decrypt(self, enc):
        aes = AES.new(str.encode(self.key), AES.MODE_ECB)  # 初始化加密器
        decrypted_text = aes.decrypt(base64.decodebytes(bytes(enc, encoding='utf8'))).decode("utf8")  # 解密
        decrypted_text = decrypted_text[:-ord(decrypted_text[-1])]  # 去除多余补位
        return decrypted_text


aes_cipher = AESCipher(KaLaiBaoConfig.api_key)
# aes_cipher = AESCipher(DayunShopConfig.api_key)
